package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.ParityFailureException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     *保存数据
     * @param dish
     * @return
     */

    @Override
    public Dish save(Dish dish) {
        //1，校验菜品数据
        checkDish(dish);
        //2，保存数据
        dishMapper.insert(dish);
        //3，返回数据
        return dish;

    }

    /**
     * dish删除
     * @param id
     */
    @Override
    public void delete(Long id) {
        //1，判断id是否为空
        if (Objects.isNull(id)){
            throw new ParityFailureException("id为空，请重试");
        }
        //2,删除菜品表中的数据
        dishMapper.deleteById(id);
    }

    /**
     * dish查询
     * @param id
     * @return
     */
    @Override
    public Dish get(Long id) {
        //1，判断id是否为空
        if (id==null){
            throw new ParityFailureException("id为空，请重试");
        }
        //2，根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        if (dish==null){
            throw new ParityFailureException("菜品不存在，请重试");
        }
        return dish;
    }

    /**
     * dish修改
     * @param dish
     */
    @Override
    public void update(Dish dish) {
        //1,校验数据
        checkDish(dish);
        //2，修改菜品数据
        dishMapper.update(dish);
    }

    /**
     * 新增菜品与口味数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //1，校验数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        checkDish(dish);
        //2,向菜品表添加一条数据
        Dish saveDish = save(dish);
        //3，获取insert语句生成的主键值
        if (saveDish.getId()==null){
            throw new ParityFailureException("id为空，请重试");
        }
        Long dishId = dish.getId();
        //4,向口味表添加多条数据
        if (!dishDTO.getFlavors().isEmpty()){
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            if (flavors != null && !flavors.isEmpty()) {
                dishFlavorMapper.insertBatch(flavors);
            }
        }

    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //判断菜品是否在出售
        for (Long id :ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus()==1){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否关联套餐
        List<Long> setmealIdsByDishId = setmealDishMapper.getSetmealIdsByDishId(ids);
        if (setmealIdsByDishId !=null && setmealIdsByDishId.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //1，校验数据
        if (id==null){
            throw new ParityFailureException("id为空，请重试");
        }
        //2，调用dish查询数据
        Dish dish = get(id);
        //3，查询口味数据
        if (Objects.isNull(dish)) {
            throw new ParityFailureException("菜品数据为null，请重试");
        }
        List<DishFlavor> flavors =dishFlavorMapper.getbyDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品
     * @param dishDTO
     */
    @Override
    public void updateWithFavorite(DishDTO dishDTO) {
        //修改菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //修改口味表
        Long dishId = dishDTO.getId();
        dishFlavorMapper.deleteByDishId(dishId);
        if (!dishDTO.getFlavors().isEmpty()) {
            List<DishFlavor> flavors = dishDTO.getFlavors();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            if (flavors != null && !flavors.isEmpty()) {
                dishFlavorMapper.insertBatch(flavors);
            }
        }
    }

    /**
     * 启售停售菜品
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);

        // 判断当前菜品是否在套餐中
        if (status == StatusConstant.DISABLE){
            List<Long> longs = new ArrayList<>();
            longs.add(id);
            List<Long> setmealIdsByDishId = setmealDishMapper.getSetmealIdsByDishId(longs);
            if (setmealIdsByDishId != null && setmealIdsByDishId.size() > 0){
                for (Long ids : setmealIdsByDishId) {
                    Setmeal setmealIds = new Setmeal().builder()
                            .id(ids)
                            .status(StatusConstant.DISABLE).build();
                    setmealMapper.update(setmealIds);
                }
            }
        }
    }

    /**
     * 条件查询菜品和口味
     * @param
     */
    @Override
    public List<Dish> listWithFlavor(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        return dishMapper.listWithFlavor(dish);
    }

    /**
     * 校验菜品数据
     * @return
     */
    @Override
    public void checkDish(Dish dish) {
        String name = dish.getName();
        if (name == null|| name.length()>10){
            throw new ParityFailureException("菜品名称长度不能超过10,或不能为空");
        }
        String description = dish.getDescription();
        if (description == null|| description.length()>200){
            throw new ParityFailureException("菜品描述长度不能超过200,或不能为空");
        }
        BigDecimal price = dish.getPrice();
        if (price == null || price.compareTo(new BigDecimal(0)) <= 0){
            throw new ParityFailureException("菜品价格不能为空，且不能小于0");
        }
        String image = dish.getImage();
        if (image == null ){
            throw new ParityFailureException("菜品图片不能为空");
        }
        Long categoryId = dish.getCategoryId();
        if (categoryId == null){
            throw new ParityFailureException("菜品分类不能为空");
        }
    }

    @Override
    public List<Dish> getBySetmealId(Long id) {
        //校验参数
        if (id==null){
            throw new ParityFailureException("id为空，请重试");
        }
        List<Dish> bySetmealId = dishMapper.getBySetmealId(id);
        return bySetmealId;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getbyDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
